package com.alpha.common.controller;

import com.alpha.core.http.Response;
import com.alpha.core.utils.CollectionUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 缓存管理接口
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Tag(name = "缓存管理")
@RestController
@RequiredArgsConstructor
public class CacheController {
    private final RedisTemplate<String, String> redisTemplate;

    @GetMapping("/caches")
    @Operation(summary = "查询微服务缓存")
    public Response<List<String>> query(@RequestParam String serviceId) {
        Set<String> keys = redisTemplate.keys(serviceId + "::*");
        return Response.success(new ArrayList<>(CollectionUtil.emptyIfNull(keys)));
    }

    @PutMapping("/caches/{serviceId}")
    @Operation(summary = "清除微服务缓存")
    public Response<Object> deleteCache(@PathVariable String serviceId) {
        redisTemplate.delete(serviceId + "::*");
        return Response.message("清除成功");
    }

    @PutMapping("/caches/{serviceId}/{key}")
    @Operation(summary = "清除指定缓存")
    public Response<Object> deleteCache(@PathVariable String serviceId, @PathVariable String key) {
        redisTemplate.delete(serviceId + "::" + key);
        return Response.message("清除成功");
    }
}